package domain;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import domain.exceptions.RequiredFieldsException;

@Entity
@Table(name = "preguntas")
public class Question extends PersistentEntity implements Comparable<Question>{

	@ManyToOne
	private User user;

	@ManyToOne
	private Item item;
	
	@Column(nullable = false)
	private Date date;
	
	@Column(nullable = false)
	private String question;
	
	private String answer;
	
	//Hibernate
	public Question() {
	}	
	
	public Question(User user, Item item, Date date, String question){
		if(question.isEmpty() || user==null || item==null || date == null ){
			throw new RequiredFieldsException();
		}
		if(item.getUser()==user)
			throw new IllegalArgumentException();
		
		this.user=user;
		this.item=item;
		this.date=date;
		this.question=question;
	}
	
	
	
	public String toString() {
		return this.question;
	}

	public User getUser() {
		return user;
	}

	public Item getItem() {
		return item;
	}

	public Date getDate() {
		return date;
	}

	public String getQuestion() {
		return question;
	}

	public String getAnswer() {
		return answer;
	}

	public void setAnswer(String answer) {
		if(answer.isEmpty()){
			throw new IllegalArgumentException();
		}
		this.answer = answer;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((date == null) ? 0 : date.hashCode());
		result = prime * result
				+ ((question == null) ? 0 : question.hashCode());
		result = prime * result + ((user == null) ? 0 : user.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Question other = (Question) obj;
		if (date == null) {
			if (other.date != null)
				return false;
		} else if (!date.equals(other.date))
			return false;
		if (question == null) {
			if (other.question != null)
				return false;
		} else if (!question.equals(other.question))
			return false;
		if (user == null) {
			if (other.user != null)
				return false;
		} else if (!user.equals(other.user))
			return false;
		return true;
	}	
	
	@Override
	public int compareTo(Question o) {
		return date.compareTo(o.getDate());
	}
}
